<Project Sdk="Microsoft.NET.Sdk">
  <Target Name="PrepareTestAssets"
          DependsOnTargets="
            GetNETCoreAppRuntimePackVersion;
            CleanTestAssets;
            GenerateTestRestoreSourcesNuGetConfig;
            CopyPotentiallyInternalPackagesForTestRestore;
            RestoreTestAssetProjects" />

  <Target Name="CleanTestAssets"
          DependsOnTargets="DetermineTestOutputDirectory">
    <!--
      Ensure installers (and therefore shared framework projects) are built first. Include used
      transitive dependencies here in case Subset is defined.
    -->
    <MSBuild
      Projects="
        @(ManagedProjectToBuild);
        @(PkgprojProjectToBuild);
        @(InstallerProjectToBuild)"
      Targets="Build" />

    <PropertyGroup>
      <TempFolderRoot>$(IntermediateOutputPath)temp\</TempFolderRoot>
      <TestTargetRid Condition="'$(TestTargetRid)' == ''">$(_HostRid)</TestTargetRid>
    </PropertyGroup>

    <ItemGroup>
      <DirsToClean Include="$(TestDir)\**\bin" />
      <DirsToClean Include="$(TestDir)\**\obj" />
      <DirsToClean Include="$(TestStabilizedLegacyPackagesDir)" />
      <DirsToClean Include="$(TestRestorePackagesPath)" />
      <DirsToClean Include="$(TempFolderRoot)$(TargetArchitecture)" />
      <DirsToClean Include="$(InternalNupkgCacheDir)" />
    </ItemGroup>

    <RemoveDir Directories="@(DirsToClean)" />

    <!-- Directory must exist even if there are no nupkgs inside to use, or NuGet fails. -->
    <MakeDir Directories="$(TestStabilizedLegacyPackagesDir)" />
  </Target>

  <Target Name="GenerateTestRestoreSourcesNuGetConfig">
    <ItemGroup>
      <RestoreTestSource Include="$(ArtifactsShippingPackagesDir)" Key="artifacts-shipping-packages" />
      <RestoreTestSource Include="$(ArtifactsNonShippingPackagesDir)" Key="artifacts-nonshipping-packages" />
      <RestoreTestSource Include="$(LibrariesShippingPackagesDir)" Condition="Exists('$(LibrariesShippingPackagesDir)')" Key="libraries-shipping-packages" />
      <RestoreTestSource Include="$(LibrariesNonShippingPackagesDir)" Condition="Exists('$(LibrariesNonShippingPackagesDir)')" Key="libraries-nonshipping-packages" />
    </ItemGroup>

    <ItemGroup Condition="'$(LibrariesPackagesDir)' != '$(LibrariesAllConfigPackagesDir)'">
      <RestoreTestSource Include="$(LibrariesAllConfigShippingPackagesDir)" Condition="Exists('$(LibrariesAllConfigShippingPackagesDir)')" Key="libraries-allconfig-shipping-packages" />
      <RestoreTestSource Include="$(LibrariesAllConfigNonShippingPackagesDir)" Condition="Exists('$(LibrariesAllConfigNonShippingPackagesDir)')" Key="libraries-allconfig-nonshipping-packages" />
    </ItemGroup>

    <ItemGroup>
      <RestoreTestSource Include="$(TestStabilizedLegacyPackagesDir)" Key="stabilized-legacy-packages" />

      <RestoreTestSource
        Condition="'$(ContinuousIntegrationBuild)' == 'true'"
        Include="$(InternalNupkgCacheDir)"
        Key="internal-nupkg-cache-packages" />
    </ItemGroup>

    <PropertyGroup>
      <TemplateNuGetConfigFile>$(RepoRoot)NuGet.config</TemplateNuGetConfigFile>

      <RestoreTestSourceConfigLines>@(RestoreTestSource -> '&lt;add key="%(Key)" value="%(Identity)" /&gt;', '%0A    ')</RestoreTestSourceConfigLines>

      <TestRestoreNuGetConfigContent>$([System.IO.File]::ReadAllText('$(TemplateNuGetConfigFile)').Replace(
        '&lt;!-- TEST_RESTORE_SOURCES_INSERTION_LINE --&gt;',
        '$(RestoreTestSourceConfigLines)'))</TestRestoreNuGetConfigContent>

      <!--
        Remove Azure DevOps feeds from NuGet.Config because they may require authenticated restore,
        which is too flaky to use in test restore. See also
        CopyPotentiallyInternalPackagesForTestRestore. https://github.com/dotnet/arcade/issues/3932
      -->
      <TestRestoreNuGetConfigContent>$([System.Text.RegularExpressions.Regex]::Replace(
        '$(TestRestoreNuGetConfigContent)',
        '&lt;add key=".+" value="https://pkgs.dev.azure.com/dnceng/internal/.+" /&gt;',
        ''))</TestRestoreNuGetConfigContent>
    </PropertyGroup>

    <WriteLinesToFile
      File="$(TestRestoreNuGetConfigFile)"
      Lines="$(TestRestoreNuGetConfigContent)"
      Overwrite="true" />
  </Target>

  <!--
    Workaround for NuGet flakiness during authenticated restore.
    https://github.com/dotnet/arcade/issues/3932

    The initial Arcade restore is stable enough to grab internal packages, but running restore
    against an authenticated feed for the test projects is too flaky. Luckily, the Arcade restore
    happens to include all the packages the test projects requires, so as a workaround, we can copy
    all nupkgs from the Arcade restore into a directory to use as a source for the test projects.
  -->
  <Target Name="CopyPotentiallyInternalPackagesForTestRestore"
          Condition="'$(ContinuousIntegrationBuild)' == 'true'">
    <Message
      Importance="High"
      Text="Copying all nupkgs in package cache to a local source for test restore..." />

    <ItemGroup>
      <PackageCacheNupkgFile Include="$(NuGetPackageRoot)*\*\*.nupkg" />
    </ItemGroup>

    <Copy SourceFiles="@(PackageCacheNupkgFile)" DestinationFolder="$(InternalNupkgCacheDir)" />
  </Target>

  <Target Name="RestoreTestAssetProjects">
    <ItemGroup>
      <TestAssetProjectToRestore Include="$(TestAssetsDir)**\*.csproj" />

      <AllTestRestoreSources Include="@(RestoreTestSource)"/>
      <AllTestRestoreSources Include="@(RestoreTestFallbackSource)"/>
    </ItemGroup>

    <Message Importance="High" Text="Running NuGet Restore for test asset projects..." />

    <MSBuild
      Projects="@(TestAssetProjectToRestore)"
      Targets="Restore"
      Properties="
        RestoreConfigFile=$(TestRestoreNuGetConfigFile);
        TestRestorePackagesPath=$(TestRestorePackagesPath);
        TestTargetRid=$(TestTargetRid);
        MNAVersion=$(NETCoreAppRuntimePackVersion)" />
  </Target>

</Project>
